
#include "ErrLog.h"
#include <fstream>
#include <string>
#include <ctime>

ErrLog g_errLog;	//Global err log object.

//Windows and UNIX have the different way of reading current working directory.
#if defined(_WIN64) || defined(_WIN32) || defined(WIN32)
#include <direct.h>
#else
#include <unistd.h>
#endif

QString ErrLog::GetCurrentWorkingDir()
{
    QString result = "";
    //Get current working directory.
    char *buffer = nullptr;
#if defined(_WIN64) || defined(_WIN32) || defined(WIN32)
    buffer = _getcwd(nullptr, 0);
#else
    buffer = getcwd(nullptr, 0);
#endif
    if (buffer != nullptr)
    {
        result = buffer;
        free(buffer);
    }

    return result;
}

ErrLog::ErrLog()
{
	//Get current working directory.
    //Working directory may get changed by other codes during program executing.

    filePath = ErrLog::GetCurrentWorkingDir();
}

void ErrLog::Write(const QString& moduleName, const QString& errLog)
{
    //File path to the log file has not correctly set, just return.
    if (filePath.isEmpty())
        return;

    std::unique_lock<std::mutex> lock(mtx);    //To be thread safe

    QString filePathName;
    filePathName.append(filePath);
    filePathName.append("/");
    filePathName.append("ErrLog.txt");

    std::ofstream file;
    file.open(filePathName.toStdString(), std::ios_base::app);
    if (file.is_open())
	{
        std::time_t now = std::time(nullptr);
        std::tm* localTime = std::localtime(&now);

        file << "TIME   :" << localTime->tm_year + 1900 << "-" << localTime->tm_mon + 1 << "-" << localTime->tm_mday;
        file << " " << localTime->tm_hour << ":" << localTime->tm_min << ":" << localTime->tm_sec << std::endl;
        file << "MODULE :" << moduleName.toStdString() << std::endl;
        file << "MESSAGE:" << errLog.toStdString() << std::endl;
        file << std::endl;

		file.close();
	}
	
    lock.unlock();
}

ErrLog *ErrLog::GetErrLogObj()
{
	return &g_errLog;
}
